import React from 'react';
import Toast from 'antd-mobile/lib/toast';
import ProductItem from 'shared/components/ProductItem';
import isSroll from 'iscroll/build/iscroll-probe';
import { fetchWishListApi } from '../api';
import './index.less';

export default class FocusWare extends React.PureComponent {
  state = {
    wishList: []
  }
  componentDidMount() {
    document.querySelector('.wrapper').addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
    this.fetchWishList();
    this.initPagination();
  }

  fetchWishList(page = 1) {
    Toast.loading('数据加载中', 5)

    fetchWishListApi({ page }).then(({ data }) => {
      Toast.hide();
      this.total = data.total;
      this.totalpage = data.totalpage;
      this.page = data.page;

      let { wishList } = this.state;
      wishList = wishList.concat(data.productlist)

      if (wishList.length < data.limit) {
        this.setState({ showloadAllMessage: true })
      }
      this.setState({ wishList }, () => {
        this.scroll.refresh();
      })
    })
  }

  initPagination() {
    this.scroll = new isSroll('.wrapper', {
      click: true,
      tap: true,
      probeType: 2,
    });

    this.scroll.on('scrollEnd', () => {
      if (this.totalpage === this.page && !this.state.showloadAllMessage) {
        this.setState({ showloadAllMessage: true }, () => {
          this.scroll.refresh();
        })
        return;
      }

      if (this.scroll.y - 400 < this.scroll.maxScrollY && this.totalpage > this.page) {
        this.onEndReached()
      }
    });
  }

  onChangeWish = ({ product_id }) => {
    const { wishList } = this.state;
    this.setState({ wishList: wishList.filter((item) => item.product_id !== product_id) });
  }

  onEndReached = () => {
    const nextPage = this.page + 1;
    this.fetchWishList(nextPage)
  }

  render() {
    const { wishList } = this.state;

    return (
      <div className="account-block focus-ware">
        <div className="account-block__title">
          我的关注
        </div>
        <div className="account-block__content">
          <div className="wrapper">
            <div className="scroller">
              {
                wishList.map((item, index)=> <ProductItem data={item} key={index} iswishPage onChangeWish={this.onChangeWish} />)
              }
              {
                this.state.showloadAllMessage &&
                  <div className="load-all" key="all">
                    <div>{wishList.length ? '全部加载完毕' : '暂无订单'}</div>
                  </div>
              }
            </div>
          </div>

        </div>
      </div>
    )
  }
}